/**
 * Useful functions.
 */

/**
 * Log error message and stack trace to console. Also accepts argument in sprintf format.
 * 
 * @param {string} message to be logged
 */
function error(message){
	if(typeof console !== "object" || typeof console.error !== "function"){
		return;
	}
	console.error(typeof message === "string"
			? sprintf.apply(this, arguments)
			: message);
}

/**
 * Log message to console. Also accepts argument in sprintf format.
 * 
 * @param {string} message to be logged
 */
function log(message){
	if(typeof console !== "object" || typeof console.log !== "function"){
		return;
	}
	console.log(typeof message === "string"
			? sprintf.apply(this, arguments)
			: message);
}

/**
 * Format string. Replace %1 - %9 with additional arguments.
 * Example:
 * 		sprintf("Meaning %1 life is %2.", of, 42); returns "Meaning of life is 42."
 * 
 * @param {string} format of resulting string
 * @returns {string} formatted string
 */
function sprintf(format){
	if(typeof format !== "string" || arguments.length === 1){
		return format;
	}
	var args = arguments;  
    var pattern = RegExp("%([1-" + (arguments.length-1) + "])", "g");
    return format.replace(pattern, function(match, index) {
        return args[index];
    });
};

/**
 * Sort array of object by given value.
 * 
 * @param {array} array
 * @param {string} by
 * @param {boolean} ascending
 */
function sortArray(array, by, ascending){
	if(typeof array !== "object" || typeof by !== "string" || typeof ascending !== "boolean"){
		return log("Illegal argument.");
	}
	array.sort(
		ascending
		? function(a, b){
			if(a[by] < b[by]) return -1;
			if(a[by] > b[by]) return 1;
			return 0;
		}
		: function(a, b){
			if(a[by] < b[by]) return 1;
			if(a[by] > b[by]) return -1;
			return 0;
		}
	);
}

function random(){
	return ~~(Math.random() * 2000000000);
}

function uploadFile(url, formId, callback) {
  var $form = $('#' + formId);
  var $parent = $form.parent();
  var $iframe = $(sprintf('<iframe id="iframe_%1"></iframe>', formId));
  $iframe.
    appendTo('body').
    contents().
    find('body').
    append($form);
  $form.submit();
  window.setTimeout(function(){
    $parent.append($form);
  }, 3000);
}
